package com.pisces.tool.util;

import java.io.Serializable;
import java.math.BigDecimal;

/**
 * 金额类型. 支持自身的四则运算，并将this返回.
 */
public class Amount implements Serializable {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private BigDecimal value;

    /**
     * 提供默认精度10
     */
    private int scale = 10;

    /**
     * double类型构造函数
     * 
     * @param value
     */
    public Amount(double value) {
        this.value = new BigDecimal(Double.toString(value));
    }

    /**
     * String类型构造函数
     * 
     * @param value
     */
    public Amount(String value) {
        this.value = new BigDecimal(value);
    }

    

    /**
     * 加法操作
     * @param d
     * @return
     */
    public Amount add(double d) {
    	
        BigDecimal v2 = new BigDecimal(Double.toString(d));
        this.value = value.add(v2);
        return this;
    }
    
    /**
     * 减法操作
     * @param d
     * @return
     */
    public Amount sub(double d) {
        BigDecimal v2 = new BigDecimal(Double.toString(d));
        this.value = value.subtract(v2);
        return this;
    }
    
    /**
     * 乘法操作
     * @param d
     * @return
     */
    public Amount mul(double d) {
        BigDecimal v2 = new BigDecimal(Double.toString(d));
        this.value = value.multiply(v2);
        return this;
    }
    
    /**
     * 除法操作
     * @param d
     * @return
     */
    public Amount div(double d) {
    	if (scale < 0) {
            throw new IllegalArgumentException("精度指定错误,请指定一个>=0的精度");
        }
        BigDecimal v2 = new BigDecimal(Double.toString(d));
        this.value = value.divide(v2, scale, BigDecimal.ROUND_HALF_UP);
        return this;
    }

    /**
     * 设置精度
     * @param scale
     */
    public void setScale(int scale) {
        this.scale = scale;
    }

    /**
     * 返回value的浮点数值
     * 
     * @return
     */
    public double doubleValue() {
        return this.value.doubleValue();
    }
    
    
}